/************************************************************/
/***************************定义变量*************************/
/** ********************************************************* */
// jQueryEasyUI对象变量
var jQueryEasyUI;
var datagridJQueryFind = "#dataGrid";
var dataFormDiv = "#dataForm";
var userRequestUrl = '/dashu-authority/user';
var roleRequestUrl = '/dashu-authority/roleController';
var comeRequestUrl = '/dashu-authority/application';
var menuRequestUrl = '/dashu-authority/menu';
var buttonOperateUrl = '/dashu-authority/buttonOperate';
var competenceUrl = "/dashu-authority/competence";
var parStr = "";



var token = getQueryStr("DASHU_AUTH_TOKEN");
var pathCode="";
var operateIdMaps= {};


$(function() {
	$("#search").click(function() {
		var param = $.fn.getFormParams(searchFrom);
		$(datagridJQueryFind).datagrid('options').queryParams = param;
		$(datagridJQueryFind).datagrid('reload');
	});
	$("#clearBtn").click(function() {
		clearFrom(searchFrom);
	});
	//$("#dlgDIV").hide();
	
	
	$("#q_application_name").combogrid({
		idField:'id', //字段   
        textField:'applicationName', //显示的字段   
        url:comeRequestUrl+'/findAllByPaging.json?DASHU_AUTH_TOKEN='+token,
        fitColumns: true,   
        striped: true,   
        editable:true,   
        pagination : true,//是否分页   
        rownumbers:true,//序号   
        collapsible:false,//是否可折叠的   
        fit: true,//自动大小   
        editable : false,// 不可编辑，只能选择   
        pageSize: 10,//每页显示的记录条数，默认为10   
        pageList: [10],//可以设置每页记录条数的列表   
        method:'post',   
        loadFilter:function(data){
			return parseDataGrid(data);
		},
        columns:[[   
            {field:'applicationName',title:'系统名称',width:400},   
        ]],
        onSelect:function(rowIndex, rowData){
        	if(rowData.id){       		
        		$('#tt').tree("loadData",  { total: 0, rows: [] });
				$(datagridJQueryFind).datagrid('loadData', { total: 0, rows: [] });
        		if($("#personnelId").val() ==null || $("#personnelId").val()=="" || $("#personnelType").val()==null || $("#personnelType").val()==""){
        			$.messager.alert("温馨提示", "请先选择所属人员信息！", "info");
        		}else{
        			tree(rowData.id);
            		$("#applicationId").val(rowData.id);
        		}      		
        	}
        }

    });
	
	
	//初始化所属人员类型
	$("#personnel_id").combobox({
		 valueField: 'personnelSore',
		 textField: 'name',  
		 panelHeight : 'auto',   
		 required : false,   
		 editable : false,// 不可编辑，只能选择   
		 data :  [ {"name":"用户","personnelSore":"personnelUser"},{"name":"角色","personnelSore":"personnelRole"}],
		 onSelect:function(data){
			 $("#personnelType").val(data.personnelSore);
			 if("personnelUser"==data.personnelSore){
				 personnelSearchData(userRequestUrl+'/findAllByPaging.json?DASHU_AUTH_TOKEN='+token,data.personnelSore);
			 }else if("personnelRole"==data.personnelSore){
				 personnelSearchData(roleRequestUrl+'/findAllByPaging.json?DASHU_AUTH_TOKEN='+token,data.personnelSore);
			 }
		 } 
	});

	$("#save").click(function(){					
		$.ajax({
			type : "POST", //提交方式 
			url : competenceUrl+'/saveMenuAuthority',
			dataType:'json',
			data:{"value":JSON.stringify(operateIdMaps),"personnelId":$("#personnelId").val(),"personnelType":$("#personnelType").val(),"applicationId":$("#applicationId").val()},
			success : function(result) {//返回数据根据结果进行相应的处理
				if (result.status == 1) {
					$.messager.alert("温馨提示", result.errorMsg, "info");
				}else{
					$.messager.alert("温馨提示", result.errorMsg, "info");
				}
				
			}
		}) 

	})

});

function personnelSearchData(url,personnelSore){
	$("#tr_deviceInfo_dataGrid").show();
	//加载所属人员类型信息
	$("#deviceInfo_dataGrid").datagrid({
		loadMsg:"数据加载中，请稍后……",
		url :url,
		width : '100%',
		pagination : true,
		pageSize : 10,
		singleSelect : true,
		striped : true,
		sortOrder : 'asc',
		rownumbers : true,
		loadFilter:function(data){
			return parseDataGrid(data);
		},
		onSelect:function(rowIndex, rowData){
			$("#personnelId").val(rowData.id);
		},
		onUnselect:function(rowIndex, rowData){
		},
		queryParams:{
		},
		columns : [ [ {
        	  field:'checkbox',
        	  checkbox:true,
          },{
			field : 'id',
  			title : 'ID',
  			width : 65,
  			align : 'center',
 			hidden : true,
  			sortable : true,
		},{
			field : 'userName',
			title : '用户名称',
			width : 90,
			align : 'center',
			hidden: "personnelUser" == personnelSore ? false : true,		
			sortable : true
		},{
			field : 'phoneNo',
			title : '电话号码',
			width : 90,
			align : 'center',
			hidden: "personnelUser" == personnelSore ? false : true,		
			sortable : true
		},{
			field : 'userAddress',
			title : '用户地址',
			width : 90,
			align : 'center',
			hidden: "personnelUser" == personnelSore ? false : true,		
			sortable : true
		},{
			field : 'roleName',
			title : '角色名称',
			width : 90,
			align : 'center',
			hidden: "personnelRole" == personnelSore ? false : true,		
			sortable : true
		},{
			field : 'parentName',
			title : '上级角色',
			width : 90,
			align : 'center',
			hidden: "personnelRole" == personnelSore ? false : true,		
			sortable : true
		}] ]
	});
}

function getChecked()
{
  var arr = [];
  var checkeds = $('#tt').tree('getChecked', 'checked');
  for (var i = 0; i < checkeds.length; i++) {
    arr.push(checkeds[i].id);
  }
  alert(arr.join(','));
}

function createOrgnizationOfTrainee()
{
    var k= getTreeSelected();
    for (var i = 0; i < k.length;i++) {
        console.log(k[i]);
    }
}
//获原始树结构所选节点的数据数组
function getTreeSelected()
{
    var nodes = $('#tt').tree('getChecked');
    var arr = new Array();
    for (var i = 0; i < nodes.length;i++) {
        arr.push(nodes[i]);
        myFuc(nodes[i]);
    }
    return arr;


    //内部递归函数
    function myFuc(n) {
        var parent = $('#tt').tree('getParent', n.target);
        if (parent == null) return;
        if (isExistItem(parent)) return;
        arr.push(parent);
        myFuc(parent);
    }
    //验证节点是否已存在数组中
    function isExistItem(item)
    {
        var flag = false;
        for (var i = 0; i < arr.length;i++)
        {
            if (arr[i] == item) {
                flag = true; break;
            }
        }
        return flag;
    }

}

function tree(applicationId){
	$("#user_district").show();
	// 初始化tree					
		$('#tt').tree({
			url : '',
			checkbox:true,
			animate:true,
			cascadeCheck:false,
			onCheck: function (node, checked) {
			},
		        onClick:function (node, data) {
		        	initDataGrid(node.id);
		        },
		        onLoadSuccess: function (node, data) {//数据加载完成事件
		        	
	            },
			onBeforeExpand : function(node, param) {
				// 加载子节点 为了避免重复加载 ，用load_flag变量来控制，0为未加载，1为已加载
				if (node.load_flag == 0) {
					var str = "path_code=" + node.id + "&type="
							+ node.child_type;
					var att_url = competenceUrl+'/getMenuTreeAuthorityAssign?DASHU_AUTH_TOKEN='+token+"&applicationId="+applicationId+"&personnelId="+$("#personnelId").val()+"&personnelType="+$("#personnelType").val()
							+ str;
					// 节点加载
					setTreeJson("#tt", att_url, node);
				}
			}
		});
		var att_url = competenceUrl+'/getMenuTreeAuthorityAssign?DASHU_AUTH_TOKEN='+token+"&applicationId="+applicationId+"&personnelId="+$("#personnelId").val()+"&personnelType="+$("#personnelType").val()
		setTreeJson("#tt", att_url, null);
}



function initDataGrid(menuId) {
	var str ="";
	var uStr="";
	$(datagridJQueryFind).datagrid({
		loadMsg:"数据加载中，请稍后……",
		url : buttonOperateUrl+'/findAllByPagingAndAuth.json?DASHU_AUTH_TOKEN='+token+'&menuId='+menuId,
		//url : baseDeviceInfoRequestUrl+'/findAllDeviceUser.json?pathCode='+pathCode,
		toolbar : [{
			text : '添加',
			iconCls : 'icon-add',
			handler : function() {
				formsubmitUrl = buttonOperateUrl+'/saveDeviceUser.json?pathCode='+pathCode;
				clearFrom(dataFormDiv);
				setDialog("#dlgDIV", '','新增');
			}
		},'-',{
			text : '删除',
			iconCls : 'icon-cancel',
			handler : function() {
				var rows = $(datagridJQueryFind).datagrid("getSelections");
				if (rows.length == 0 ) {
					$.messager.alert("操作提示", "请至少选择一行", "info");
				} else {
					var ids = [];
					for (var i = 0; i < rows.length; i++) {
						ids.push(rows[i].id);
					}
					$.messager.confirm('确认','您确认想要删除选中的权限数据？',function(r) {
						if (r) {
							$.ajax({
								type : "POST",
								dataType : 'html',
								url : baseDeviceInfoRequestUrl+'/deleteDeviceUserByIds.json?pathCode='+pathCode+'&ids='+ids,
								success : function(data) {
									var obj = eval('('+ data+ ')');
									console.log(JSON.stringify(obj));
									if (obj.status == 1) {
										$.fn.messageInfoTip(data);
										$(datagridJQueryFind).datagrid('reload');
									}
								},
								error: function(textStatus){
									if(console){
										console.error("ajax出现异常："+textStatus);
									}
									alert(textStatus);
								}
							});
						}else{
							return false;
						}
					});
				}
		}} ],
		width : '100%',
		pagination : true,
		pageSize : 10,
		singleSelect : false,
		striped : true,
		sortOrder : 'asc',
		rownumbers : true,
		onLoadSuccess : function(data) {
			$(datagridJQueryFind).datagrid('clearSelections');
			var nodes = $('#tt').tree('getSelected');
			if(nodes!=null){
				 var rowData = data.rows; 
				 var c= operateIdMaps[menuId];
				 console.log(c);
				 if(rowData!=null && rowData.length>0){
				    $.each(rowData,function(index,row){//遍历JSON 
				    	if(operateIdMaps!=null && Object.getOwnPropertyNames(operateIdMaps).length>0){
				    		if(typeof(c) != undefined && c!=null){
				    			if(checkProduct(Number(c),Number(row.soreNum))){
					    			$("#dataGrid").datagrid("selectRow", index);  
					    		}
				    		}
						}  
				    });  
				 }
			}
			// auths这个参数在apiCommon.js文件中
			
			if(auths!=null){
				 var rowData = data.rows; 
				var menuAuth = auths[menuId];
				 if(rowData!=null && rowData.length>0){
					 $.each(rowData,function(index,row){//遍历JSON 
						 if(checkProduct(Number(menuAuth),Number(row.soreNum))){
								$("#dataGrid").datagrid("selectRow", index);  
								
								
							}; 
					 });
					
					
				 }
			}
			
		},
		onCheck:function(rowIndex,rowData){
			
		},
		onUncheck:function(rowIndex,rowData){
		},
		loadFilter:function(data){
			return parseDataGrid(data);
		},
		onLoadError : function() {
		},

		onClickRow:function(rowIndex,rowData){
			
			var checks = $("#dataGrid").datagrid('getChecked');
			var nodes = $('#tt').tree('getSelected');
			
			//获取父级
			var nodePar = $('#tt').tree('getParent', nodes.target);
			
			if(checks!=null && checks.length>0){				
				for (var i = 0; i < checks.length; i++) {
					if(rowData.menuId==null||nodes.id==checks[i].menuId){					
						var nodesss = $('#tt').tree('find', nodes.id); 						
						$('#tt').tree('check',nodesss.target); 
						if (nodePar != null) {              
							$("#tt").tree('check', nodePar.target);
						}
					}				
				}
			}else{
				if(rowData.menuId==null||nodes.id==rowData.menuId){
					var nodesss = $('#tt').tree('find', nodes.id); 
		        	if(nodesss.checked==false){
		        		 $('#tt').tree('check',nodesss.target); 
		        	}else{
		        		 $('#tt').tree('uncheck',nodesss.target); 
		        	}if (nodePar != null) {
		        		if(nodePar.checked==false){
			        		 $('#tt').tree('check',nodePar.target); 
			        	}else{
			        		 $('#tt').tree('uncheck',nodePar.target); 
			        	}
					}	
				}
				 str="";
				 parStr = "";
				 delete operateIdMaps[nodePar.id];
				 delete operateIdMaps[nodes.id]; 
				
			}
			
			
			if(isChecked(rowData)){	 //选中
				var checks  = $("#dataGrid").datagrid('getChecked');
				console.log(checks);
				str = "";
				for (var i = 0; i < checks.length; i++) {	
				  if(str!=null && ""!=str){
					  str += ","+checks[i].soreNum;
					}else{
						str += checks[i].soreNum;
					}
				}
				  
				  //父级加权重值
				  if(nodePar!=null){
				  if("2"==rowData.soreNum){
					  if(parStr!=null && ""!=parStr){
							parStr += ","+rowData.soreNum;
						}else{
							parStr += rowData.soreNum;
						}  
				  }else if("3"==rowData.soreNum){
					  if(parStr!=null && ""!=parStr){
							parStr += ","+rowData.soreNum;
						}else{
							parStr += rowData.soreNum;
						}  
				  }else if("4"==rowData.soreNum){
					  if(parStr!=null && ""!=parStr){
							parStr += ","+rowData.soreNum;
						}else{
							parStr += rowData.soreNum;
						}  
				  }else if("5"==rowData.soreNum){
					  if(parStr!=null && ""!=parStr){
							parStr += ","+rowData.soreNum;
						}else{
							parStr += rowData.soreNum;
						}  
				  }else if("1"==rowData.soreNum){
					  if(parStr!=null && ""!=parStr){
							parStr += ","+rowData.soreNum;
						}else{
							parStr += rowData.soreNum;
						}  
				  }
				}
				  
				  
			 }else{  //没选中	
				 
				var checks  = $("#dataGrid").datagrid('getChecked');				 
				str = "";				
				//父级加权重值
				parStr="";
				
					for (var i = 0; i < checks.length; i++) {						
						if(str!=null && ""!=str){
							str += ","+checks[i].soreNum;
						}else{
							str += checks[i].soreNum;
					}
										
						//父级加权重值
						if(nodePar!=null){
							  if("2"==checks[i].soreNum){
								  if(parStr!=null && ""!=parStr){
										parStr += ","+checks[i].soreNum;
									}else{
										parStr += checks[i].soreNum;
									}  
							  }else if("3"==checks[i].soreNum){
								  if(parStr!=null && ""!=parStr){
										parStr += ","+checks[i].soreNum;
									}else{
										parStr += checks[i].soreNum;
									}  
							  }else if("4"==checks[i].soreNum){
								  if(parStr!=null && ""!=parStr){
										parStr += ","+checks[i].soreNum;
									}else{
										parStr += checks[i].soreNum;
									}  
							  }else if("5"==checks[i].soreNum){
								  if(parStr!=null && ""!=parStr){
										parStr += ","+checks[i].soreNum;
									}else{
										parStr += checks[i].soreNum;
									}  
							  }else if("1"==checks[i].soreNum){
								  if(parStr!=null && ""!=parStr){
										parStr += ","+checks[i].soreNum;
									}else{
										parStr += checks[i].soreNum;
									}  
							  }
							}
				 }
					
			 }
			
			
			if(rowData.soreNum==1){  //为第一条数据要走一次“选中”的步骤
				if(isChecked(rowData)){
					$("#dataGrid").datagrid("selectRow", 0); 
					var checks  = $("#dataGrid").datagrid('getChecked');
					str = "";
					for (var i = 0; i < checks.length; i++) {	
					  if(str!=null && ""!=str){
						  str += ","+checks[i].soreNum;
						}else{
							str += checks[i].soreNum;
						}
					}
					//父级加权重值
					if(nodePar!=null){
						if(parStr!=null && ""!=parStr){
							parStr += ","+rowData.soreNum;
						}else{
							parStr += rowData.soreNum;
						}
					}
				}else{
					$("#dataGrid").datagrid("unselectRow", 0);
					var checks  = $("#dataGrid").datagrid('getChecked');
					str = "";
					//父级加权重值
					 parStr="";
					 
						for (var i = 0; i < checks.length; i++) {
							
							//当前节点加权重值
							if(str!=null && ""!=str){
								str += ","+checks[i].soreNum;
							}else{
								str += checks[i].soreNum;
						}
							 
							//父级加权重值
							 if(nodePar!=null){
								  if("2"==checks[i].soreNum){
									  if(parStr!=null && ""!=parStr){
											parStr += ","+checks[i].soreNum;
										}else{
											parStr += checks[i].soreNum;
										}  
								  }else if("3"==checks[i].soreNum){
									  if(parStr!=null && ""!=parStr){
											parStr += ","+checks[i].soreNum;
										}else{
											parStr += checks[i].soreNum;
										}  
								  }else if("4"==checks[i].soreNum){
									  if(parStr!=null && ""!=parStr){
											parStr += ","+checks[i].soreNum;
										}else{
											parStr += checks[i].soreNum;
										}  
								  }else if("5"==checks[i].soreNum){
									  if(parStr!=null && ""!=parStr){
											parStr += ","+checks[i].soreNum;
										}else{
											parStr += checks[i].soreNum;
										}  
								  }else if("1"==checks[i].soreNum){
									  if(parStr!=null && ""!=parStr){
											parStr += ","+checks[i].soreNum;
										}else{
											parStr += checks[i].soreNum;
										}  
								  }
							}
					 }
				}
			}else{	
				var checks  = $("#dataGrid").datagrid('getChecked');
				if(checks!=null && checks.length>0){
					var rowsss=$('#dataGrid').datagrid('getRows')[0]; //获取第一条数据
					if(!isChecked(rowsss)){
						$("#dataGrid").datagrid("selectRow", 0);
						if(str!=null && ""!=str){
							str += ","+rowsss.soreNum;
						}else{
							str += rowsss.soreNum;
						}
						
						//父级加权重值
						if(nodePar!=null){
							if(parStr!=null && ""!=parStr){
								parStr += ","+rowsss.soreNum;
							}else{
								parStr += rowsss.soreNum;
							}
						}
					}
				}
				
			}
			
			
			
			if(auths!=null ){
				if(auths[menuId]!=null){
					delete auths[menuId];
				}
					operateIdMaps = auths;
				
				
				//operateIdMaps[parseInt(menuId)]=getProduct(aStrs);	
			}
			
			if(str!=null && ""!=str){
				var aStrs = str.split(",");
				operateIdMaps[parseInt(menuId)]=getProduct(aStrs);
			}
			
			if(parStr!=null && ""!=parStr ){
				var parStrs = parStr.split(",");
				operateIdMaps[parseInt(nodePar.id)]=getProduct(parStrs);
			}

			
			
			console.log(operateIdMaps);
			
		},
		columns : [ [ 
		             	{
		             		field : 'ck',
		             		checkbox : true
		             	},
				       {	field : 'id',
							title : 'ID',
							width : 65,
							align : 'center',
							hidden : true,
							sortable : true
						},{
							field : 'name',
							title : '名称',
							width : 90,
							align : 'center',
							sortable : true
						},{
							field : 'menuName',
							title : '菜单名称',
							width : 90,
							align : 'center',
							sortable : true
						},{
							field : 'soreNum',
							title : '编号',
							width : 90,
							align : 'center',
							sortable : true
						},{
							field : 'createTime',
							title : '创建时间 ',
							width : 180,
							align : 'center',
							sortable : true
						}, {
							field : 'updateTime',
							title : '更新时间 ',
							width : 180,
							align : 'center',
							sortable : true
						}
				         ] ]
	});
}

function isChecked(rowData){  
    var rows = $("#dataGrid").datagrid('getSelections');  
    for(var i=0;i<rows.length;i++){  
        if(rowData.id==rows[i].id){  
        return true;  
        }  
    }  
    return false;  
} 

function arrValueIndex(arrValue,val) {  
    for (var i = 0; i < arrValue.length; i++) {  
        if (arrValue[i].soreNum == val) return i;  
    }  
    return -1;  
}; 
 


function clearFrom(cform){
	$(cform).form("clear");
}

function submitForm() {
	$('#dataForm').form('submit', {
		url : formsubmitUrl,
		ajax : true,
		onSubmit:function(){
			return $(this).form('validate');
		},
		success : function(data) {
			var obj = eval('(' + data + ')');
			var status = obj.status;
			console.log(JSON.stringify(obj));
			if (status == 1) {
				$.fn.messageInfoTip(data);
				$('#dlgDIV').dialog('close');
				$(datagridJQueryFind).datagrid('reload');
			} else {
				$.fn.messageInfoTip(data);
			}
		}
	});
}
function setDialog(dialogDiv, hrefHtml, title) {
	$(dialogDiv).show();
	$("#tr_userInfo_dataGrid").hide();
	$(dialogDiv).dialog({
		title : title,
		width : 600,
		height : 400,
		closed : false,
		cache : false,
		modal : true,
		buttons : [ {
			text : '保存',
			iconCls : 'icon-ok',
			handler:function(){
				$("#personnelIds").val(personnelIds);			
				submitForm();
			}
		}, {
			text : '重置',
			iconCls : 'icon-clear',
			handler : function() {
				clearFrom(dataFormDiv);
			}
		}, {
			text : '关闭',
			iconCls : 'icon-remove',
			handler : function() {
				$(dialogDiv).dialog('close');
			}
		} ]
	});
}


function addParNodeVal(rowData,nodes,str){
	var nodePar = $('#tt').tree('getParent', nodes.target);  //父级
	if(nodePar!=null){
		var strs= new Array(); //定义一数组 
		strs=str.split(","); //字符分割 
		for (i=0;i<strs.length ;i++ ) { 
			if("1"==strs[i]){
				if(parStr!=null && ""!=parStr){
					parStr += ","+1;
				}else{
					parStr += 1;
				}
			}else if("2"==strs[i]){
				if(parStr!=null && ""!=parStr){
					parStr += ","+2;
				}else{
					parStr += 2;
				}
			}else if("3"==strs[i]){
				if(parStr!=null && ""!=parStr){
					parStr += ","+3;
				}else{
					parStr += 3;
				}
			}else if("4"==strs[i]){
				if(parStr!=null && ""!=parStr){
					parStr += ","+4;
				}else{
					parStr += 4;
				}
			}else if("5"==strs[i]){
				if(parStr!=null && ""!=parStr){
					parStr += ","+5;
				}else{
					parStr += 5;
				}
			}
		} 
		operateIdMaps[parseInt(nodePar.id)]=parStr;
	}
}

